# -*- coding: utf-8 -*-
# @author: edgardeng
# @date:   2021-05-08
# @file:   [websocket] https://websockets.readthedocs.io/en/stable/

""" 上传文件目录 和 文件数据 """
import asyncio
import json
import os
import time
import sys
import websockets
from websockets.protocol import State

now = lambda: time.time()
now_str = lambda: time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())


async def file_manage():
    uri = "ws://localhost:8765/abc"
    try:
        async with websockets.connect(uri) as websocket:
            while websocket.state != State.CLOSED:
                message = await websocket.recv()  # result , data
                msg = json.loads(message)
                print('-' * 20)
                print(msg)
                if 'action' in msg:
                    action = msg.get('action')
                    dir_a = msg.get('params')
                    if action == 'file_list':
                        reply = {'result': 'file_list', 'data': json_file_list(dir_a)}
                        print('--'*20, 'reply')
                        print(reply)
                        await websocket.send(json.dumps(reply))
                    elif action == 'file_data':
                        print('--'*20, 'reply')
                        await websocket.send(get_file_data(dir_a))

    except Exception as e:
        print('error', e)


def json_file_list(dir_file):
    data = []
    for name in os.listdir(dir_file):
        path = os.path.join(dir_file, name)
        data.append({
            'name': name,
            'is_dir': os.path.isdir(path),
            'size': os.path.getsize(path)
        })
    return data


def get_file_data(path_file):
    with open(path_file, 'rb') as file:
        words = file.read()
        return words


if __name__ == '__main__':
    user = str(sys.argv[1]) if len(sys.argv) >= 2 else 'none'

    t0 = time.time()
    print('start', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t0)))
    loop = asyncio.get_event_loop()

    # task = asyncio.ensure_future(sanic_channel_status())
    loop.run_until_complete(file_manage())  # 单任务

    # tasks = [asyncio.ensure_future(hello_sanic2(str(i))) for i in range(5)]
    # loop.run_until_complete(asyncio.wait(tasks)) # 多任务

    # for i in range(10):
    #     # loop.run_until_complete(hello(str(i)))
    #     loop.run_until_complete(hello_sanic(str(i)))

    t1 = time.time()
    print('end', time.strftime('%Y-%M-%D %H:%M:%S', time.localtime(t1)), t1 - t0)
